import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from .models import Video

class MyHandler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory:
            file_name = os.path.basename(event.src_path)
            if file_name.endswith(('.mp4', '.avi', '.mkv')):
                file_path = os.path.join('videos/', file_name)
                Video.objects.create(name=file_name, path=file_path)  # 将文件信息添加到数据库
                print(f"文件已创建并添加到数据库: {file_name}")

    def on_deleted(self, event):
        if not event.is_directory:
            file_name = os.path.basename(event.src_path)
            Video.objects.filter(name=file_name).delete()  # 从数据库中删除文件信息
            print(f"文件已删除并从数据库移除: {file_name}")
    

def start_watchdog(path):
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=False)

    observer.start()
    print(f"开始监控: {path}")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()